#include <ulib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stat.h>
#include <file.h>
#include <dir.h>
#include <unistd.h>

#define printf(...)                 fprintf(1, __VA_ARGS__)
#define FILELENGTH  12  //"hello cuero\0"

static int
safe_open(const char *path, int open_flags) {
    int fd = open(path, open_flags);
    assert(fd >= 0);
    return fd;
}

static struct stat *
safe_fstat(int fd) {
    static struct stat __stat, *stat = &__stat;
    int ret = fstat(fd, stat);
    assert(ret == 0);
    return stat;
}

static int
safe_read(int fd, void *data, size_t len) {
    int ret = read(fd, data, len);
    assert(ret = FILELENGTH);
    return ret;
}

static int
safe_write(int fd, void *data, size_t len) {
    int ret = write(fd, data, len);
    assert(ret == FILELENGTH);
    return ret;
}

static void
safe_diff(unsigned char buf1[], unsigned char buf2[], size_t len) {
    int i;
    for (i = 0; i < len; ++i) {
        assert(buf1[i] == buf2[i]);
    }
}

static unsigned char buffer[4096];
static unsigned char buffer2[4096];

int
main(void) {
    int fd = safe_open("disk1:/testfile", O_RDONLY);
    struct stat *stat = safe_fstat(fd);
    assert(stat->st_size == FILELENGTH);
    
    memset(buffer, 0, sizeof(buffer));
    int ret1 = safe_read(fd, buffer, sizeof(buffer));
    
    //copy from sfs to fat32
    int destfd = safe_open("disk0:/testfile", O_RDWR | O_CREAT);
    safe_write(destfd, buffer, ret1);
    close(destfd);
    destfd = safe_open("disk0:/testfile", O_RDONLY);
    
    assert(sizeof(buffer) == sizeof(buffer2));
    int fd2 = safe_open("disk1:/testfile2", O_RDWR | O_CREAT);
    memset(buffer2, 0, sizeof(buffer));
    int ret2 = safe_read(destfd, buffer2, sizeof(buffer2));
    
    //diff, and copy from fat32 to sfs
    assert(ret1 == ret2);
    safe_diff(buffer, buffer2, ret1);
    safe_write(fd2, buffer2, ret1);
    close(fd2);
    fd2 = safe_open("disk1:/testfile2", O_RDONLY);
    
    //diff
    memset(buffer2, 0, sizeof(buffer));
    ret2 = safe_read(fd2, buffer2, sizeof(buffer2));
    assert(ret1 == ret2);
    safe_diff(buffer, buffer2, ret1);

    //unlink
    assert(unlink("disk1:/testfile2") == 0);
    assert(unlink("disk0:/testfile") == 0);
    printf("cross_filetest1 pass.\n");
    return 0;
}
